package com.example.mcp.controller;

import com.example.mcp.service.McpClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * MCP客户端控制器 - 提供MCP客户端功能的REST接口
 */
@RestController
@RequestMapping("/api/mcp")
@CrossOrigin(origins = "*")
public class McpClientController {

    private static final Logger logger = LoggerFactory.getLogger(McpClientController.class);

    @Autowired
    private McpClientService mcpClientService;

    /**
     * 健康检查 - 检查MCP客户端状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        logger.info("🔍 检查MCP客户端健康状态");
        
        Map<String, Object> response = Map.of(
                "status", mcpClientService.isInitialized() ? "UP" : "DOWN",
                "initialized", mcpClientService.isInitialized(),
                "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(response);
    }

    /**
     * Ping测试 - 测试MCP连接
     */
    @GetMapping("/ping")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> ping() {
        logger.info("🏓 执行MCP Ping测试");
        
        return mcpClientService.ping().thenApply(result -> {
            Map<String, Object> response = Map.of(
                    "success", !result.startsWith("错误") && !result.startsWith("异常"),
                    "result", result,
                    "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(response);
        });
    }

    /**
     * 获取所有聊天记录
     */
    @GetMapping("/conversations")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getAllConversations() {
        logger.info("📋 获取所有聊天记录");
        
        return mcpClientService.getAllConversations().thenApply(result -> {
            Map<String, Object> response = Map.of(
                    "success", !result.startsWith("错误") && !result.startsWith("异常"),
                    "conversations", result,
                    "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(response);
        });
    }

    /**
     * 根据ID获取聊天记录
     */
    @GetMapping("/conversations/{conversationId}")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getConversationById(
            @PathVariable String conversationId) {
        logger.info("🔍 获取聊天记录详情: {}", conversationId);
        
        return mcpClientService.getConversationById(conversationId).thenApply(result -> {
            Map<String, Object> response = Map.of(
                    "success", !result.startsWith("错误") && !result.startsWith("异常"),
                    "conversation", result,
                    "conversationId", conversationId,
                    "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(response);
        });
    }

    /**
     * 根据会话ID获取消息列表
     */
    @GetMapping("/conversations/{conversationId}/messages")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> getMessagesByConversationId(
            @PathVariable String conversationId) {
        logger.info("📋 获取会话消息列表: {}", conversationId);
        
        return mcpClientService.getMessagesByConversationId(conversationId).thenApply(result -> {
            Map<String, Object> response = Map.of(
                    "success", !result.startsWith("错误") && !result.startsWith("异常"),
                    "messages", result,
                    "conversationId", conversationId,
                    "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(response);
        });
    }

    /**
     * 发送消息
     */
    @PostMapping("/conversations/{conversationId}/messages")
    public CompletableFuture<ResponseEntity<Map<String, Object>>> sendMessage(
            @PathVariable String conversationId,
            @RequestBody Map<String, String> messageRequest) {
        
        String sender = messageRequest.get("sender");
        String content = messageRequest.get("content");
        
        logger.info("📤 发送消息到会话: {}, 发送者: {}", conversationId, sender);
        
        return mcpClientService.sendMessage(conversationId, sender, content).thenApply(result -> {
            Map<String, Object> response = Map.of(
                    "success", !result.startsWith("错误") && !result.startsWith("异常"),
                    "result", result,
                    "conversationId", conversationId,
                    "sender", sender,
                    "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(response);
        });
    }
}
